//
//  BandConfigModel.swift
//  DaRings
//
//  Created by 尹琼 on 2023/2/27.
//

import UIKit
import SQLite
import HandyJSON
import SwiftDate
import SQLiteValueExtension
import MYModule


open class BandConfigModel: NSObject, MYSQLiteTableiabe, HandyJSON {
    
    public var adress: String = ""
    
    public var id: Int64 = 0
    
    public var date: Date = Date().sqlDate()
    
    
    public var configId: Int = 0
    
    /// localName
    public var name: String = ""
    
    public var mcu: Int = 0
    
    public var version: String = ""
    
    public var logo: [String] = []
    
    public var colors: [String] = []
    
    /// 数据更新时间
    public var updated_at: Double = 0
    
    public var isEmpty: Bool {
        return logo.isEmpty || colors.isEmpty
    }
    
    
    public required override init() {}
    
    public func mapping(mapper: HelpingMapper) {
        
        mapper <<< self.configId <-- "id"
        
    }
    
    
    public static func model(with configId: Int) ->BandConfigModel? {
        
        let query = table.filter(self.expression_configId == configId)
        guard let row = try? db.pluck(query) else {
            return nil
        }
        return BandConfigModel.deserialize(from: row)
        
    }
    
    public static func first() ->BandConfigModel? {
        return all().first
    }
    
    public static func last() ->BandConfigModel? {
        return all().last
    }
    
    public static func all() ->[BandConfigModel] {
        
        let query = table.order(expression_configId.asc)
        guard let rows = try? db.prepare(query) else {
            return []
        }
        return [BandConfigModel].deserialize(from: rows)
        
    }
    
    
    public func updateData() {
        
        
        guard let model = BandConfigModel.model(with: configId) else {
            self.insert()
            return
        }
        
        /// 数据库更新时间更新，不要更新数据库
        if model.updated_at > self.updated_at {
            return
        }
        
        self.update()
        
    }
    
}

//public struct BandConfigLogoModel: HandyJSON, StringValueExpressible {
//    /// 戒指颜色
//    var color: String = ""
//    /// 戒指图片
//    var img: String = ""
//    
//    public static func fromStringValue(_ stringValue: String) -> BandConfigLogoModel {
//        return deserialize(from: stringValue) ?? BandConfigLogoModel()
//    }
//    
//    public var stringValue: String {
//        return self.toJSONString() ?? ""
//        
//    }
//    
//    public init() {}
//}

